package com.ysz.gulimall.ware.service.impl;

import com.ysz.common.constant.WareConstant;
import com.ysz.gulimall.ware.entity.PurchaseDetailEntity;
import com.ysz.gulimall.ware.service.PurchaseDetailService;
import com.ysz.gulimall.ware.service.WareSkuService;
import com.ysz.gulimall.ware.vo.MergeVo;
import com.ysz.gulimall.ware.vo.PurchaseDoneVo;
import com.ysz.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysz.common.utils.PageUtils;
import com.ysz.common.utils.Query;

import com.ysz.gulimall.ware.dao.PurchaseDao;
import com.ysz.gulimall.ware.entity.PurchaseEntity;
import com.ysz.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    PurchaseDetailService detailService;

    @Resource
    WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnreceivePurchase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //todo 确认采购单状态1/0才能合并
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(item -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        detailService.updateBatchById(collect);
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    /**
     * @description:
     * @param: [ids] 采购单id
     * @return: void
     * @author 杨圣志
     * @date: 2023/10/31 20:46
     */
    @Transactional
    @Override
    public void received(List<Long> ids) {
        List<PurchaseEntity> entities = ids.stream().map(this::getById)
                .filter(item -> item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                        item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
                .peek(item -> {
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    item.setUpdateTime(new Date());
                }).collect(Collectors.toList());
        //改变采购单状态
        this.updateBatchById(entities);
        //改变采购项
        entities.forEach(item->{
           List<PurchaseDetailEntity> detailEntities =  detailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> collect = detailEntities.stream().map(detail -> {
                PurchaseDetailEntity purchaseEntity = new PurchaseDetailEntity();
                purchaseEntity.setId(detail.getId());
                purchaseEntity.setStatus(WareConstant.PurchaseDetailEnum.BUYING.getCode());
                return purchaseEntity;
            }).collect(Collectors.toList());
            detailService.updateBatchById(collect);
        });

    }

    @Override
    @Transactional
    public void done(PurchaseDoneVo purchaseDoneVo) {
        Long id = purchaseDoneVo.getId();
        //改变采购项状态
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> updateList = new ArrayList<>();
        boolean flag = true;
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseDetailEnum.ERROR.getCode()){
                flag = false;
                detailEntity.setStatus(WareConstant.PurchaseDetailEnum.ERROR.getCode());
            }else {
                detailEntity.setStatus(WareConstant.PurchaseDetailEnum.FINISH.getCode());
                //入库
                PurchaseDetailEntity entity = detailService.getById(item.getItemId());

                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            updateList.add(detailEntity);
        }
        detailService.updateBatchById(updateList);

        //修改采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.ERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

}
